//
//  WBNetwork+Extension.swift
//  微博
//
//  Created by 蒋丙爽 on 2021/4/30.
//  Copyright © 2021 Jiang. All rights reserved.
//

import Foundation


//MARK:-封装新浪微博的网络请求方法,不关心网络实现细节-
extension WBNetworkManager {
    
    /// 加载微博字典数组
    //list: 微博字典数组
    /*
     since_id:若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。  下拉刷新最新的
     max_id:若指定此参数，则返回ID小于或等于max_id的微博，默认为0。 上拉刷新以前的数据
     isSuccess : 是否成功
     */
    func statusList(since_id:Int64=0,max_id:Int64=0, completion:@escaping(_ list:[[String:AnyObject]]?,_ isSuccess:Bool)->()) {
        //
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //Swift 中 Int 可以转成AnyObject类型，但是Int64不行
//        let params = ["since_id":"\(since_id)"]
        let params = ["since_id":(since_id as AnyObject),
                      "max_id":((max_id > 0 ? max_id - 1 : 0) as AnyObject)
                    ]
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            print("获取数组--->\(json)")
            //从json中获取statuses 字典数组
            //如果as? 失败,result = nil
            let jsonCopy = json as? [String:AnyObject]
            //提示:服务器返回的字典数组,就是按照时间的倒序排序的
            let result = jsonCopy?["statuses"] as? [[String:AnyObject]]
            
//            for i in 0..<result!.count{
//                let dic = result?[i]
//                print("dic--->\(dic?["text"])")
//            }
            
            print("result--->\(result)")
            completion(result,isSuccess)
        }
        
    }
    
    //返回新浪微博的未读数量
    func unreadCount(completion:@escaping(_ count:Int)->()) {
        
        guard let uid = uid else {
            return;
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid":uid as AnyObject]
        tokenRequest(URLString: urlString, parameters: params) { json, isSuccess in
            print("--获取未读数-->\(json)")
            let dict = json as? [String : AnyObject]
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
        
        
    }
    
    
    
}
